//引入pinia、登录API、ElementPlus
import { defineStore } from 'pinia'
import {login} from '@/api/login'
import { ElMessage } from 'element-plus'

//创建store
export const userStore = defineStore('userLoginInfo',{
    //定义登录状态及登录信息
    state: () =>({
        user:{
            userName: '' as String,
            account:'' as String,
            roles:[] as any
        },
        token:null,
        isLogin:false
    }),

    //获取用户信息
    getters:{
        getUser: (state)=> state.user,
        getLoginStatus:(state)=> state.isLogin,
        getUserName:(state)=>state.user?.userName || 'admin',
        getToken:(state)=>state.token
    },

    //定义操作方法
    actions:{
        //登录方法
        async userLogin(account: String,password: String){
            //调用登录方法
            let result = await login({'userName':account,'password':password}) as any;
            console.log(result)
            //登录成功
            if(result.code==200){
                this.user={
                    userName:result.data.userName,
                    account:result.data.account,
                    roles:result.data.roles
                },
                this.isLogin=true
                this.token=result.token

                //信息提示
                ElMessage({
                    showClose: true,
                    message: result.msg,
                    type: 'success',
                })
            }else{
                //登录失败，提示错误信息
                ElMessage({
                    showClose: true,
                    message: result.msg,
                    type: 'error',
                })
            }
        },

        //注销方法
        loginOut(){
            this.user={
                userName:'',
                account:'',
                roles:[]
            },
            this.isLogin=false
            this.token=null

            //信息提示
            ElMessage({
                showClose: true,
                message: '登出成功',
                type: 'success',
            })
        }
    }
})